//
//  FKApplyRefundVC.m
//  WanTao
//
//  Created by Macbook Pro on 2019/4/2.
//  Copyright © 2019 Macbook Pro. All rights reserved.
//

#import "FKApplyRefundVC.h"
#import "FKOrderListCell.h"
#import "FKSelectPhotoView.h"
#import "FKRefundReasonPopVC.h"
#import "FKCustomPresentationVC.h"
#import "BCustomPresentationController.h"

@interface FKApplyRefundVC ()<UITableViewDataSource, UITableViewDelegate, FKSelectPhotoViewDelegate>

@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) UITableViewCell *reasonCell;
@property (nonatomic, weak) UITextField *reasonField;

@property (nonatomic, strong) UITableViewCell *priceCell;
@property (nonatomic, weak) UILabel *priceLabel;
@property (nonatomic, weak) UILabel *maxPriceLabel;
@property (nonatomic, weak) UILabel *tipLabel;
@property (nonatomic, weak) UITextField *remarkField;

@property (nonatomic, weak) UIView *footer;
@property (nonatomic, weak) FKSelectPhotoView *addPhotoView;

@property (nonatomic, assign) NSInteger sections;
@property (nonatomic, strong) NSDictionary *data;
@property (nonatomic, strong) NSMutableDictionary *param;

@end

@implementation FKApplyRefundVC

- (NSMutableDictionary *)param
{
    if (!_param) {
        _param = [NSMutableDictionary dictionary];
    }
    return _param;
}

- (void)dealloc
{
    NSLog(@"---销毁了----");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"申请退款";
    self.param[@"order_goods_id"] = self.goodsId;
    
    UIView *bottomView = [[UIView alloc] init];
    [self.view addSubview:bottomView];
    bottomView.backgroundColor = [UIColor whiteColor];
    
    UIButton *commitBtn = [UIButton fk_btnWithTarget:self action:@selector(commitBtnClicked) font:fk_adjustFont(15) normalTitle:@"提交申请" normalTitleColor:[UIColor whiteColor] selectedTitle:nil selectedTitleColor:nil normalImg:nil selectedImg:nil bgImg:[UIImage imageNamed:@"bg_main"] selectedBgImg:nil];
    [bottomView addSubview:commitBtn];
    [commitBtn fk_viewCornerRadius:fk_adjustW(20) borderWidth:0 borderColor:nil];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 退款原因
    UITableViewCell *reasonCell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, fk_adjustW(45))];
    self.reasonCell = reasonCell;
    reasonCell.selectionStyle = UITableViewCellSelectionStyleNone;
    reasonCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    UILabel *reasonTitle = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkColor333333 text:@"退款原因"];
    [reasonCell.contentView addSubview:reasonTitle];
    
    UITextField *reasonField = [[UITextField alloc] init];
    [reasonCell.contentView addSubview:reasonField];
    self.reasonField = reasonField;
    reasonField.font = fk_adjustFont(14);
    reasonField.placeholder = @"请选择";
    reasonField.textAlignment = NSTextAlignmentRight;
    reasonField.userInteractionEnabled = false;
    
    // 退款金额
    UITableViewCell *priceCell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, fk_adjustW(45))];
    self.priceCell = priceCell;
    priceCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    UILabel *priceTitle = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkColor333333 text:@"退款金额:"];
    [priceCell.contentView addSubview:priceTitle];
    
    UILabel *priceLabel = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkMainColor];
    [priceCell.contentView addSubview:priceLabel];
    self.priceLabel = priceLabel;
    
    UIView *centerView = [[UIView alloc] init];
    [priceCell.contentView addSubview:centerView];
    centerView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    UILabel *maxPriceLabel = [UILabel fk_labelWithFont:fk_adjustFont(11) textColor:fkColor999999];
    [centerView addSubview:maxPriceLabel];
    self.maxPriceLabel = maxPriceLabel;
    
    UILabel *tipLabel = [UILabel fk_labelWithFont:fk_adjustFont(11) textColor:fkMainColor text:@"爆款商品退款需扣除一定的手续费哦~"];
    [centerView addSubview:tipLabel];
    self.tipLabel = tipLabel;
    
    UILabel *remarkTitle = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkColor333333 text:@"退款说明："];
    [priceCell.contentView addSubview:remarkTitle];
    
    UITextField *remarkField = [[UITextField alloc] init];
    [priceCell.contentView addSubview:remarkField];
    self.remarkField = remarkField;
    remarkField.font = fk_adjustFont(14);
    remarkField.placeholder = @"选填";
    
    // footer
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, fk_adjustW(140))];
    footer.backgroundColor = [UIColor whiteColor];
    self.footer = footer;
    self.tableView.tableFooterView = footer;
    
    UILabel *footerTitle = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkColor333333 text:@"上传凭证："];
    [footer addSubview:footerTitle];
    
    FKSelectPhotoView *addPhotoView = [[FKSelectPhotoView alloc] initWithFrame:CGRectMake(12, fk_adjustW(46), fkScreenW-24, fk_adjustW(82))];
    [footer addSubview:addPhotoView];
    self.addPhotoView = addPhotoView;
    addPhotoView.superVC = self;
    addPhotoView.delegate = self;
    addPhotoView.column = 4;
    addPhotoView.addBtnBgImg = [UIImage imageNamed:@"photo"];
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.height.offset(fk_adjustW(58));
    }];
    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.right.offset(-15);
        make.height.offset(fk_adjustW(40));
        make.centerY.offset(0);
    }];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.bottom.equalTo(bottomView.mas_top);
    }];
    [reasonTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.centerY.offset(0);
    }];
    [reasonField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.offset(0);
        make.width.offset(fk_adjustW(240));
    }];
    [centerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(fk_adjustW(45));
        make.left.right.offset(0);
        make.height.offset(fk_adjustW(50));
    }];
    [maxPriceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.top.offset(fk_adjustW(10));
    }];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(maxPriceLabel);
        make.bottom.offset(fk_adjustW(-10));
    }];
    CGFloat priceTitleW = [priceTitle.text sizeWithAttributes:@{NSFontAttributeName : priceTitle.font}].width;
    priceTitle.frame = CGRectMake(12, 0, priceTitleW, fk_adjustW(45));
    
    [priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(priceTitle.mas_right).offset(8);
        make.top.bottom.equalTo(priceTitle);
        make.right.offset(-12);
    }];
    [remarkTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(priceTitle);
        make.top.equalTo(centerView.mas_bottom);
        make.bottom.offset(0);
    }];
    [remarkField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(priceLabel);
        make.top.bottom.equalTo(remarkTitle);
    }];
    [footerTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.top.offset(0);
        make.bottom.equalTo(addPhotoView.mas_top);
    }];
    
    [self loadData];
}

- (void)commitBtnClicked
{
    [self.view endEditing:true];
    
    if (self.reasonField.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请选择退款原因"];
        return;
    }
    
    [self orderRefund];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sections;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        FKOrderListCell *cell = [FKOrderListCell cellWith:tableView];
//        cell.data = self.datas[indexPath.section];
        cell.data = self.data[@"goods"];
        return cell;
    } else if (indexPath.section == 1) {
        return self.reasonCell;
    } else if (indexPath.section == 2) {
        return self.priceCell;
    }
    return nil;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return fk_adjustW(98);
    } else if (indexPath.section == 1) {
        return fk_adjustW(45);
    } else if (indexPath.section == 2) {
        return fk_adjustW(140);
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 10;
    }
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.data) {
        if (indexPath.section == 1) {
//            FKRefundReasonPopVC *vc = [[FKRefundReasonPopVC alloc] init];
//            vc.datas = self.data[@"reasons"];
//            [self presentViewController:vc animated:true completion:nil];
            
            
            FKRefundReasonPopVC *vc = [[FKRefundReasonPopVC alloc] init];
            vc.datas = self.data[@"reasons"];
//            UIViewController *vc = [[UIViewController alloc] init];
            BCustomPresentationController *presentationVC = [[BCustomPresentationController alloc] initWithPresentedViewController:vc presentingViewController:self];
            vc.transitioningDelegate = presentationVC;
            [self presentViewController:vc animated:YES completion:NULL];
            fkWeakSelf(self);
            vc.selectedReason = ^(NSDictionary * _Nonnull data) {
                weakself.param[@"reason"] = data[@"title"];
                weakself.reasonField.text = data[@"title"];
            };
        }
    }
}

#pragma mark - FKSelectPhotoViewDelegate
- (void)selectPhotoViewAdjustFrame:(FKSelectPhotoView *)view
{
    self.footer.fk_height = fk_adjustW(46) + view.fk_height + fk_adjustW(12);
    self.tableView.tableFooterView = self.footer;
}

#pragma mark - 网络请求
- (void)loadData
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"order_goods_id"] = self.goodsId;
    [FKHttpTool postWithSuffix:@"/OrderRefund/create" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            self.sections = 3;
            self.data = result.data;
            [self.tableView reloadData];
            
            NSDictionary *refund = result.data[@"refund"];
            self.priceLabel.text = fkFORMAT(@"￥%@", refund[@"refund_price"]);
            NSString *maxPrice = fkFORMAT(@"最多￥%@", refund[@"refund_price"]);
            if ([refund[@"refund_freight"] floatValue] != 0) {
                maxPrice = [maxPrice stringByAppendingString:fkFORMAT(@" 含运费:￥%@", refund[@"refund_freight"])];
            }
            self.maxPriceLabel.text = maxPrice;
            if ([refund[@"is_explosion"] isEqualToString:@"1"]) {
                self.tipLabel.text = [self.tipLabel.text stringByAppendingString:fkFORMAT(@" 手续费:￥%@", refund[@"explosion_hand_fee"])];
            }
        }
    } failure:nil];
}

- (void)orderRefund
{
    self.param[@"content"] = self.remarkField.text;
    fkWeakSelf(self);
    [self uploadImages:^(NSArray *urls) {
//        if (urls.count > 0) weakself.param[@"images"] = [urls componentsJoinedByString:@","];
        if (urls.count > 0) weakself.param[@"images"] = urls;
        [FKHttpTool postWithSuffix:@"/OrderRefund/store" param:self.param success:^(FKBaseResult *result) {
            if (result.isSuccess) {
                [SVProgressHUD showSuccessWithStatus:@"退款申请提交成功"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOrderListVC" object:nil];
                [weakself.navigationController popViewControllerAnimated:true];
            }
        } failure:nil];
    }];
}

- (void)uploadImages:(void(^)(NSArray *urls))success
{
    if (self.addPhotoView.images.count == 0) {
        success([NSArray array]);
        return;
    }
    NSMutableDictionary *images = [NSMutableDictionary dictionary];
    for (UIImage *image in self.addPhotoView.images) {
        NSString *key = fkFORMAT(@"image_%zd", [self.addPhotoView.images indexOfObject:image]);
        images[key] = image;
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"dir"] = @"refund";
    [FKHttpTool uploadFile:@"m=Home&c=Mine&a=uploadImg" param:param files:images progress:^(NSProgress *progress) {
        [SVProgressHUD showProgress:progress.fractionCompleted];
    } success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            if (success) {
                success(result.data);
            }
        }
    } failure:nil];
}

@end
